Python Programming Lab · Exp-5

Understanding Core Data Structures

A definitive guide to Lists, Tuples, and Dictionaries in Python with practical problem-solving applications.

📦 Lists 🔒 Tuples 🔑 Dictionaries

Use ← → keys or swipe to navigate

Session Overview

What We Cover Today

01

Data Structures

Theory on Lists, Tuples, and Dictionaries.

02

List Algorithms

Runner-up scores and Frequency counting.

03

Dictionary Mapping

Key-Value bindings for Movies and Students.

04

Building Apps

Creating Contact Book and To-do Manager loops.

Foundation

Python Lists

Lists are used to store multiple items in a single variable. They are ordered, mutable (changeable), and allow duplicate values.

# Creating a list
fruits = ["apple", "banana", "cherry"]

# Mutating a list
fruits.append("orange")   # Adds to the end
fruits[1] = "mango"       # Modifies index 1
fruits.pop(0)             # Removes item at index 0

print(fruits)             # Output: ['mango', 'cherry', 'orange']

Ordered

Items have a defined order, which will not change. If you add new items, they are placed at the end.

Changeable

We can change, add, and remove items in a list after it has been created.

Foundation

Python Tuples

Tuples are identical to lists, but with one critical difference: they are immutable (unchangeable). Once a tuple is created, you cannot change its values.

# Creating a tuple
coordinates = (10.5, 20.8)

# Tuples can be accessed like lists
print(coordinates[0])   # Output: 10.5

# ERROR: coordinates[0] = 11.5 
# "tuple object does not support item assignment"

When to use Tuples instead of Lists?

  • When your data should NOT be modified accidentally (e.g., configurations, coordinates).
  • Tuples perform memory allocation faster than lists. They are more efficient.
  • They can be used as keys in Dictionaries since they are immutable.
Foundation

Python Dictionaries

Dictionaries are used to store data values in key:value pairs. They are ordered (as of Python 3.7), changeable, and do NOT allow duplicate keys.

# Creating a dictionary
car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

# Accessing attributes via keys
print(car["brand"])     # Output: Ford
car["year"] = 2020      # Updates value
  • Keys: Must be immutable types (String, Number, Tuple) and unique.
  • Values: Can be of any data type (Lists, objects, even other Dicts).
  • Using .get('key') is safer than [] because it avoids KeyErrors if missing.
Problem 1

Frequency of Values from 0-3

Task: Scan n values in the range 0-3 and print the number of times each value has occurred.

n = int(input("Enter number of values to read: "))
values = []

for i in range(n):
    val = int(input("Enter a value (0-3): "))
    if 0 <= val <= 3:
        values.append(val)
    else:
        print("Ignored: Value must be between 0 and 3.")

# Check count for 0, 1, 2, 3
for x in range(4):
    freq = values.count(x)
    print(f"Value {x} occurred {freq} times")
Enter number of values to read: 5 Enter a value (0-3): 1 Enter a value (0-3): 1 Enter a value (0-3): 3 Enter a value (0-3): 0 Enter a value (0-3): 1 Value 0 occurred 1 times Value 1 occurred 3 times Value 2 occurred 0 times Value 3 occurred 1 times
Problem 2

Tuple Average Calculation

Task: Create a tuple to store n numeric values and find the average of all values.

n = int(input("Enter number of values: "))
temp_list = []

# Lists are easier to build dynamically than Tuples
for i in range(n):
    num = float(input("Enter numeric value: "))
    temp_list.append(num)

# Convert list to tuple
num_tuple = tuple(temp_list)

if len(num_tuple) > 0:
    avg = sum(num_tuple) / len(num_tuple)
    print(f"Tuple: {num_tuple}")
    print(f"Average: {avg:.2f}")

💡 Dynamic Tuple Generation

Because tuples are immutable, you cannot use .append() on them. A common pattern is appending to a temporary List and type-casting it to a Tuple at the very end using the tuple() constructor.

Problem 3

The Runner-Up Score

Task: Input a list of scores for N students. Find the score of the runner-up.

n = int(input("N = "))
input_string = input("Scores= ")

# The split() splits the string by spaces.
# List comprehension converts strings to integers.
scores = [int(x) for x in input_string.split()]

# Remove duplicates to handle multiple maximum scores
unique_scores = list(set(scores))

# Sort in descending order
unique_scores.sort(reverse=True)

# The 0th index is highest, 1st index is runner-up
print(unique_scores[1])
N = 5 Scores= 2 3 6 6 5 5
Problem 4

Students & Cities Dictionary

Task: Create a dictionary linking Names (keys) to Cities (values) and execute multiple queries.

persons = {"Alice": "Paris", "Bob": "London", "Charlie": "Paris"}

# a) Display all names (Keys)
print("Names:", list(persons.keys()))

# b) Display all cities (Values)
print("Cities:", list(persons.values()))

# c) Display student name and city
for name, city in persons.items():
    print(f"{name} -> {city}")

# d) Count number of students in each city
city_count = {}
for city in persons.values():
    # .get(city, 0) handles cases where city key is not made yet
    city_count[city] = city_count.get(city, 0) + 1

print("Counts:", city_count)
Problem 5

Nested Movie Dictionary

Task: Create a dictionary holding another dictionary (Name -> {Year, Director, Cost, Earnings}). Query specific movies.

movies = {
    "Inception": {"year":2010, "dir":"Nolan", "cost":160, "earn":836},
    "Avatar":    {"year":2009, "dir":"Cameron","cost":237, "earn":2900},
    "Dune":      {"year":2021, "dir":"Villeneuve","cost":165, "earn":400}
}
print("--- Movies Before 2015 ---")
for name, info in movies.items():
    if info["year"] < 2015:  print(name)

print("--- Movies Making Profit ---")
for name, info in movies.items():
    if info["earn"] > info["cost"]: print(name)

print("--- Movies by Nolan ---")
for name, info in movies.items():
    if info["dir"] == "Nolan": print(name)
Problem 6

Contact Book Manager

Task: Create a persistent CRUD (Create, Read, Update, Delete) program using a Dictionary.

contacts = {}
while True:
    ch = int(input("1.Add 2.Search 3.Delete 4.Exit : "))
    
    if ch == 1:
        name = input("Name: ")
        contacts[name] = input("Phone: ")
        
    elif ch == 2:
        name = input("Name to search: ")
        print("Found:", contacts.get(name, "Not Found"))
        
    elif ch == 3:
        name = input("Name to delete: ")
        if name in contacts:
            del contacts[name]
            print("Deleted.")
            
    elif ch == 4: break
Problem 7

Todo List Manager

Task: Create an infinite loop permitting users to push and pop tasks out of a List array.

todos = []
while True:
    print("1.Add Task  2.View Tasks  3.Remove Task  4.Exit")
    ch = int(input("Choice: "))
    
    if ch == 1:
        todos.append(input("Enter new task: "))
        
    elif ch == 2:
        for idx, task in enumerate(todos):
            print(f"Task {idx+1}: {task}")
            
    elif ch == 3:
        idx = int(input("Enter Task Number to Remove: ")) - 1
        if 0 <= idx < len(todos):
            removed = todos.pop(idx)
            print(f"{removed} successfully removed.")
        else:
            print("Invalid ID.")
            
    elif ch == 4: break
Wrap Up

Open your Python IDE

Understanding Data Structures is arguably the most important step of python scripting. It is imperative to perform these labs yourself.

Build Apps in Colab
Use arrow keys or swipe to navigate